package logic

import (
	"2103A-server/house/internal/model"
	"context"
	"net/http"
	"time"

	"2103A-server/house/house"
	"2103A-server/house/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateLogic {
	return &CreateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateLogic) Create(in *house.CreateRequest) (*house.Response, error) {
	// todo: add your logic here and delete this line

	id := in.Id
	// 添加的逻辑
	var data model.House
	data.UserId = in.UserId
	data.AreaId = in.AreaId
	data.Title = in.Title
	data.Price = in.Price
	data.IndexImageUrl = in.ImageUrl
	data.Ctime = time.Now()

	if in.Id > 0 {
		data.Id = in.Id
		// 更新
		err := l.svcCtx.HouseModel.Update(context.Background(), &data)
		if err != nil {
			return &house.Response{
				Code: http.StatusCreated,
				Msg:  "更新失败" + err.Error(),
			}, nil
		}
	} else {
		// 添加
		// 调用添加的方法、实现添加
		res, err := l.svcCtx.HouseModel.Insert(context.Background(), &data)
		if err != nil {
			return &house.Response{
				Code: http.StatusCreated,
				Msg:  "添加失败" + err.Error(),
			}, nil
		}
		id, err = res.LastInsertId() //获取新添加的id

	}
	var d []*house.CreateRequest

	var rsp = &house.CreateRequest{
		Id: id,
	}
	d = append(d, rsp)
	return &house.Response{
		Code: http.StatusOK,
		Msg:  "操作成功",
		Data: d,
	}, nil
}
